import { fetchGoodsList } from '../../../services/good/fetchGoodsList';
import { fetchCategoryProducts } from '../../../services/product/fetchCategoryProducts';
import Toast from 'tdesign-miniprogram/toast/index';

const initFilters = {
  overall: 1,
  sorts: '',
  layout: 0,
};

Page({
  data: {
    goodsList: [],
    layout: 0,
    sorts: '',
    overall: 1,
    show: false,
    minVal: '',
    maxVal: '',
    filter: initFilters,
    hasLoaded: false,
    loadMoreStatus: 0,
    loading: true,
    categoryId: null, // 分类ID
    categoryName: '', // 分类名称
    currentSort: 'overall', // 当前排序方式：overall-综合，price-价格
    priceSortType: 'asc', // 价格排序类型：asc-升序，desc-降序
  },

  pageNum: 1,
  pageSize: 30,
  total: 0,

  handleFilterChange(e) {
    const { layout, overall, sorts } = e.detail;
    this.pageNum = 1;
    
    // 更新排序状态
    let currentSort = 'overall';
    let priceSortType = 'asc';
    
    if (overall === 1) {
      currentSort = 'overall';
    } else if (sorts === 'asc') {
      currentSort = 'price';
      priceSortType = 'asc';
    } else if (sorts === 'desc') {
      currentSort = 'price';
      priceSortType = 'desc';
    }
    
    this.setData({
      layout,
      sorts,
      overall,
      currentSort,
      priceSortType,
      loadMoreStatus: 0,
    });
    this.init(true);
  },

  generalQueryData(reset = false) {
    const { filter, keywords, minVal, maxVal } = this.data;
    const { pageNum, pageSize } = this;
    const { sorts, overall } = filter;
    const params = {
      sort: 0, // 0 综合，1 价格
      pageNum: 1,
      pageSize: 30,
      keyword: keywords,
    };

    if (sorts) {
      params.sort = 1;
      params.sortType = sorts === 'desc' ? 1 : 0;
    }

    if (overall) {
      params.sort = 0;
    } else {
      params.sort = 1;
    }
    params.minPrice = minVal ? parseFloat(minVal) : 0; // 直接使用元为单位
    params.maxPrice = maxVal ? parseFloat(maxVal) : undefined; // 直接使用元为单位
    if (reset) return params;
    return {
      ...params,
      pageNum: pageNum + 1,
      pageSize,
    };
  },

  async init(reset = true) {
    const { loadMoreStatus, goodsList = [], categoryId, currentSort, priceSortType, minVal, maxVal } = this.data;
    
    if (loadMoreStatus !== 0) return;
    
    this.setData({
      loadMoreStatus: 1,
      loading: true,
    });
    
    try {
      let result;
      
      if (categoryId) {
        // 如果有分类ID，调用综合查询接口
        console.log('调用分类商品查询接口，分类ID:', categoryId, '排序:', currentSort);
        result = await this.fetchProductsWithQuery(categoryId, currentSort, priceSortType, minVal, maxVal);
      } else {
        // 否则使用原来的商品列表接口
        const params = this.generalQueryData(reset);
        result = await fetchGoodsList(params);
      }
      
      if (categoryId) {
        // 分类商品接口直接返回数组
        this.setData({
          goodsList: result,
          loadMoreStatus: result.length > 0 ? 2 : 0, // 分类商品暂不支持分页，直接显示全部
          hasLoaded: true,
          loading: false,
        });
      } else {
        // 原来的商品列表逻辑
        const code = 'Success';
        const data = result;
        if (code.toUpperCase() === 'SUCCESS') {
          const { spuList, totalCount = 0 } = data;
          if (totalCount === 0 && reset) {
            this.total = totalCount;
            this.setData({
              emptyInfo: {
                tip: '抱歉，未找到相关商品',
              },
              hasLoaded: true,
              loadMoreStatus: 0,
              loading: false,
              goodsList: [],
            });
            return;
          }

          const _goodsList = reset ? spuList : goodsList.concat(spuList);
          const _loadMoreStatus = _goodsList.length === totalCount ? 2 : 0;
          this.pageNum = this.generalQueryData(reset).pageNum || 1;
          this.total = totalCount;
          this.setData({
            goodsList: _goodsList,
            loadMoreStatus: _loadMoreStatus,
          });
        } else {
          this.setData({
            loading: false,
          });
          wx.showToast({
            title: '查询失败，请稍候重试',
          });
        }
      }
    } catch (error) {
      console.error('加载商品失败:', error);
      this.setData({
        loading: false,
        goodsList: [],
        loadMoreStatus: 0,
      });
      wx.showToast({
        title: '加载商品失败',
        icon: 'none',
      });
    }
    
    this.setData({
      hasLoaded: true,
      loading: false,
    });
  },

  onLoad(options) {
    const { categoryId, categoryName } = options || {};
    
    if (categoryId) {
      const decodedCategoryName = decodeURIComponent(categoryName || '商品分类');
      this.setData({
        categoryId: parseInt(categoryId),
        categoryName: decodedCategoryName,
      });
      
      // 设置页面标题为分类名称
      wx.setNavigationBarTitle({
        title: decodedCategoryName
      });
      
      console.log('分类商品列表页面 - 分类ID:', categoryId, '分类名称:', decodedCategoryName);
    }
    
    this.init(true);
  },

  onReachBottom() {
    const { categoryId, goodsList } = this.data;
    const { total = 0 } = this;
    
    // 如果是分类商品页面，暂不支持分页加载
    if (categoryId) {
      return;
    }
    
    // 原有的分页逻辑
    if (goodsList.length === total) {
      this.setData({
        loadMoreStatus: 2,
      });
      return;
    }
    this.init(false);
  },

  handleAddCart() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '点击加购',
    });
  },

  tagClickHandle() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '点击标签',
    });
  },

  // 调用后端综合查询接口
  async fetchProductsWithQuery(categoryId, currentSort, priceSortType, minVal, maxVal) {
    return new Promise((resolve, reject) => {
      // 构建查询参数
      const params = {
        categoryId: categoryId
      };
      
      // 添加价格区间参数
      if (minVal) {
        params.minPrice = parseFloat(minVal); // 直接使用元为单位
      }
      if (maxVal) {
        params.maxPrice = parseFloat(maxVal); // 直接使用元为单位
      }
      
      // 添加排序参数
      if (currentSort === 'price') {
        params.sortBy = 'price';
        params.sortType = priceSortType;
      } else if (currentSort === 'sales') {
        params.sortBy = 'sales';
        params.sortType = 'desc';
      }
      
      console.log('查询参数:', params);
      
      wx.request({
        url: 'http://localhost:1002/index/products/query',
        method: 'GET',
        data: params,
        header: {
          'Content-Type': 'application/json'
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data) {
            console.log('后端返回的商品数据:', res.data);
            
            // 映射后端数据字段到前端需要的格式
            const mappedData = res.data.map((item, index) => {
              const productData = {
                spuId: item.productId || index,
                thumb: item.imageUrl || 'https://cdn-we-retail.ym.tencent.com/tsr/goods/nz-09a.png',
                title: item.productName || '商品名称',
                price: item.price || 0, // 直接使用后端返回的价格，不除以100
                originPrice: null,
                tags: [],
              };
              return productData;
            });
            
            console.log('映射后的商品数据:', mappedData);
            resolve(mappedData);
          } else {
            console.error('查询商品失败:', res);
            reject(new Error('查询商品失败'));
          }
        },
        fail: (err) => {
          console.error('网络请求失败:', err);
          reject(err);
        }
      });
    });
  },

  gotoGoodsDetail(e) {
    const { index } = e.detail;
    const { spuId } = this.data.goodsList[index];
    console.log('商品列表页商品点击，商品ID:', spuId);
    wx.navigateTo({
      url: `/pages/goods/details/index?productId=${spuId}`,
    });
  },

  showFilterPopup() {
    this.setData({
      show: true,
    });
  },

  showFilterPopupClose() {
    this.setData({
      show: false,
    });
  },

  onMinValAction(e) {
    const { value } = e.detail;
    this.setData({ minVal: value });
  },

  onMaxValAction(e) {
    const { value } = e.detail;
    this.setData({ maxVal: value });
  },

  reset() {
    this.setData({ 
      minVal: '', 
      maxVal: '',
      currentSort: 'overall',
      priceSortType: 'asc'
    });
    // 重置后重新加载数据
    this.pageNum = 1;
    this.setData({
      goodsList: [],
      loadMoreStatus: 0,
    });
    this.init(true);
  },

  confirm() {
    const { minVal, maxVal } = this.data;
    let message = '';
    let isValid = true;
    
    // 验证价格输入
    if (minVal && maxVal) {
      if (parseFloat(minVal) > parseFloat(maxVal)) {
        message = '最低价格不能大于最高价格';
        isValid = false;
      } else {
        message = `价格范围${minVal}-${maxVal}`;
      }
    } else if (minVal && !maxVal) {
      message = `价格最小是${minVal}`;
    } else if (!minVal && maxVal) {
      message = `价格范围是0-${maxVal}`;
    } else {
      message = '请输入价格范围';
      isValid = false;
    }
    
    if (message) {
      Toast({
        context: this,
        selector: '#t-toast',
        message,
      });
    }
    
    if (isValid) {
      // 应用价格筛选
      this.pageNum = 1;
      this.setData(
        {
          show: false,
          goodsList: [],
          loadMoreStatus: 0,
        },
        () => {
          this.init(true);
        },
      );
    }
  },
});